package cn.tedu.csmall.product.ex.handler;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        log.warn("程序运行过程中出现ServiceException,将统一处理。");
        log.warn("异常信息：{}", e.getMessage());
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult hangleBindException(BindException e) {
        log.warn("程序运行过程中出现BindException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
//        StringJoiner stringJoiner = new StringJoiner(",","请求参数格式错误，","!");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError error : fieldErrors){
//            stringJoiner.add(error.getDefaultMessage());
//        }
        FieldError fieldError = e.getFieldError();
        String message = fieldError.getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, message);
    }

    @ExceptionHandler
    public JsonResult constraintViolationHandller(ConstraintViolationException e) {
        log.warn("程序运行过程中出现ConstraintViolationException,将统一处理。");
        String message = "";
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            message = constraintViolation.getMessage();
        }

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, message);
    }

    String message = "";

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e) {
        log.warn("程序运行过程中出现Throwable，将统一处理");
        log.warn("异常类型：{}", e.getClass());
        log.warn("异常类信息{}", e.getMessage());
        String message = "【开发阶段专用】服务端出现新的异常，请检查服务端控制器，并添加该类型异常处理机制";
        e.printStackTrace();
        return JsonResult.fail(ServiceCode.ERR, message);
    }
}
